﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using TomanuExtensions;
using YAXLib;

namespace RaytracerLib.Materials
{
    public class MaterialsList : ObjectsList<Material>
    {
        private Material FindSame(Material a_material)
        {
            return this.FirstOrDefault(m => m.Equals(a_material));
        }

        public Material AddOrFind(Material a_material)
        {
            var mt = FindSame(a_material);
            if (mt != null)
                return mt;
            a_material.Name = a_material.Name.FindUniqueName(
                from m in this select m.Name);
            Add(a_material);
            return a_material;
        }

        public void RemoveNotUsed()
        {
            var m1 = from obj in Scene.RenderableObjects
                     from m in obj.Materials
                     select m;

            var m2 = this.Except(m1);

            foreach (var m in m2.ToList())
                Remove(m);
        }

        public override bool Remove(Material a_material)
        {
            if (Scene.RenderableObjects.Any(r => Object.ReferenceEquals(r.DefaultMaterial, a_material)))
                throw new InvalidOperationException("");

            return base.Remove(a_material); 
        }

        public override string ToString()
        {
            return String.Format("Materials; Count: {0}", this.Count());
        }
    }
}